<template>
  <div>
    <div class="app-container">
      <div class="page_header">{{ID?'编辑':'添加'}}方案</div>
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="130px">
          <el-col :span="12">
            <el-row>
              <el-col :span="24">
                <el-form-item label="方案名称" prop="schemeName">
                  <el-input v-model="formData.schemeName" placeholder="请输入方案名称" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="内部名称" prop="schemeInName">
                  <el-input v-model="formData.schemeInName" placeholder="请输入内部名称" :maxlength="50" clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="施工类型" prop="schemeFun">
                  <el-select v-model="formData.schemeFun" placeholder="请选择施工类型" clearable :style="{width: '100%'}">
                    <el-option v-for="(item, index) in schemeFunOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="方案类型" prop="schemeType">
                  <el-select v-model="formData.schemeType" placeholder="请选择方案类型" clearable :style="{width: '100%'}">
                    <el-option v-for="(item, index) in schemeTypeOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-form-item label="产品" prop="products" style="margin-bottom:0;">
                <div style="display:flex;align-items:flex-start;">
                  <el-button style="height:32px;margin-top: 2px;" size="small" type="primary" icon="el-icon-plus" @click="handleProAdd">增加</el-button>
                  <div style="margin-left:10px;width: calc(100% - 85px);">
                    <div class="product_per_row" v-for="(pro,index) of formData.products" :key="index">
                      <el-col :span="4">
                        <el-form-item
                          label-width="60px"
                          label="名称"
                          :prop="`products[${index}].productId`"
                          :rules="{
                            required:true, message: '请选择', trigger: 'change'
                          }"
                        >
                          <el-select v-model="pro.productId" placeholder="请选择" clearable :style="{width: '100%'}" @change="handleProChange($event,pro)">
                            <el-option v-for="item in productsOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="4">
                        <el-form-item label-width="60px" label="单价" :prop="`products[${index}].schemeProductPrice`">
                          <el-input disabled v-model="pro.schemeProductPrice" :style="{width: '100%'}"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="4">
                        <el-form-item
                          label-width="60px"
                          label="数量"
                          :prop="`products[${index}].schemeProductCount`"
                          :rules="[{
                            required: true,
                            message: '请输入数量',
                            trigger: 'change'
                          },{
                            pattern:  /^[1-9]\d*$/,
                            message: '格式有误',
                            trigger: 'change'
                          }]"
                        >
                          <el-input-number
                            :style="{width: '100%'}"
                            v-model="pro.schemeProductCount"
                            :min="1"
                            @change="handleProCountChange($event,pro)"
                            placeholder="请输入"
                            :step="1"
                          ></el-input-number>
                        </el-form-item>
                      </el-col>
                      <el-col :span="4">
                        <el-form-item label-width="60px" label="总价" :prop="`products[${index}].schemeProductZprice`">
                          <el-input disabled v-model="pro.schemeProductZprice" :style="{width: '100%'}"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="4" v-show="false">
                        <el-form-item label-width="60px" label="名称" :prop="`products[${index}].schemeProductName`">
                          <el-input disabled v-model="pro.schemeProductName" :style="{width: '100%'}"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="1">
                        <el-button
                          v-show="formData.products.length !== 1"
                          style="margin-left: 10px;"
                          size="small"
                          type="danger"
                          icon="el-icon-minus"
                          circle
                          @click="handleProMinus(index)"
                        ></el-button>
                      </el-col>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="24">
                <el-form-item label="人工价" prop="schemePersonPrice">
                  <el-input v-model="formData.schemePersonPrice" placeholder="请输入人工价" :maxlength="20" clearable :style="{width: '100%'}">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="预设面积" prop="schemeArea">
                  <el-input v-model="formData.schemeArea" placeholder="请输入预设面积" :maxlength="20" clearable :style="{width: '100%'}">
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="质保期" prop="schemeGp">
                  <el-input v-model="formData.schemeGp" placeholder="请输入质保期" :maxlength="20" clearable :style="{width: '100%'}">
                    <template slot="append">年</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="总部成本价" prop="schemeZbcost">
                  <el-input v-model="formData.schemeZbcost" placeholder="请输入总部成本价" :maxlength="20" clearable :style="{width: '100%'}">
                    <template slot="append">元/m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="经销商成本价" prop="schemeDealerCost">
                  <el-input v-model="formData.schemeDealerCost" placeholder="请输入经销商成本价" :maxlength="20" clearable :style="{width: '100%'}">
                    <template slot="append">元/m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="家装成本价" prop="schemeJzcost">
                  <el-input v-model="formData.schemeJzcost" placeholder="请输入家装成本价" :maxlength="20" clearable :style="{width: '100%'}">
                    <template slot="append">元/m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="方案售价" prop="schemePrice">
                  <el-input v-model="formData.schemePrice" placeholder="请输入方案售价" :maxlength="20" clearable :style="{width: '100%'}">
                    <template slot="append">元/m²</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="商品介绍" prop="schemeContent">
                  <editor v-model="formData.schemeContent" :min-height="192" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-form-item label="经销商" prop="areas">
                <div style="display:flex;align-items:flex-start;">
                  <el-button style="height:32px;margin-top: 2px;" size="small" type="primary" icon="el-icon-plus" @click="handleAreaDataAdd">增加</el-button>
                  <div style="margin-left: 10px; width: calc(100% - 85px);">
                    <div class="product_per_row" v-for="(area,index) of formData.areas" :key="index">
                      <el-col :span="5">
                        <el-form-item label-width="60px" label="地区" :prop="`areas[${index}].schemeAreaArr`">
                          <CityPicker :withAll="true" clearable placeholder="请选择" @change="handleCityPickChange($event,area)" v-model="area.schemeAreaArr" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="4">
                        <el-form-item label-width="60px" label="名称" :prop="`areas[${index}].dealerId`">
                          <el-select v-model="area.dealerId" placeholder="请选择" clearable :style="{width: '100%'}">
                            <el-option v-for="item in area.dealerList" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-button
                        v-show="formData.areas.length !== 1"
                        style="margin-left: 10px;"
                        size="small"
                        type="danger"
                        icon="el-icon-minus"
                        circle
                        @click="handleAreaDataMinus(index)"
                      ></el-button>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-form-item size="large">
              <el-button type="primary" :disabled="pending" @click="submitForm">提交</el-button>
              <el-button type="primary" :disabled="pending" @click="submitAssess">方案评估</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <el-dialog title="方案评估" :visible.sync="dialogVisible" width="1200px">
        <div class="assess_box">
          <div class="assess_topData">
            <div>套餐成本</div>
            <div>预设面积（m²）：{{assessData.topData.row1}}</div>
            <div>材料总费用（元）：{{assessData.topData.row2}}</div>
            <div>人工总费用（元）：{{assessData.topData.row3}}</div>
          </div>
          <div class="assess_data">
            <div class="per_data" v-for="per of assessData.data" :key="per.sort">
              <div>{{per.explain}}</div>
              <div>{{per.row1}}</div>
              <div>{{per.row2}}</div>
              <div>{{per.row3}}</div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDealerList } from '@/api/dealer/index'
import { getSchemeProduct, getSchemeAssess } from '@/api/scheme/index'
import { createCURD } from '@/api/sys'
const schemeApi = createCURD('scheme')
import CityPicker from '@/components/cityPicker'
import Editor from '@/components/Editor'

export default {
  name: 'Schemeedit',
  components: {
    CityPicker,
    Editor
  },
  data() {
    return {
      formData: {
        schemeName: undefined,
        schemeInName: undefined,
        schemeFun: undefined,
        schemeType: undefined,
        schemePersonPrice: undefined,
        schemeArea: undefined,
        schemeGp: undefined,
        schemeZbcost: undefined,
        schemeDealerCost: undefined,
        schemeJzcost: undefined,
        schemePrice: undefined,
        schemeContent: undefined,

        products: [
          {
            schemeProductName: undefined,
            schemeProductPrice: undefined,
            schemeProductCount: undefined,
            schemeProductZprice: undefined,
            productId: undefined
          }
        ],
        areas: [
          {
            schemeAreaArr: [],
            dealerId: undefined,
            dealerList: []
          }
        ]
      },
      rules: {
        products: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个产品',
            trigger: 'change'
          }
        ],
        schemeName: [
          {
            required: true,
            message: '请输入方案名称',
            trigger: 'blur'
          }
        ],
        schemeInName: [
          {
            required: true,
            message: '请输入内部名称',
            trigger: 'blur'
          }
        ],
        schemeFun: [
          {
            required: true,
            message: '请选择施工类型',
            trigger: 'change'
          }
        ],
        schemeType: [
          {
            required: true,
            message: '请选择方案类型',
            trigger: 'change'
          }
        ],
        schemePersonPrice: [
          {
            required: true,
            message: '请输入人工价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        schemeArea: [
          {
            required: true,
            message: '请输入预设面积',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        schemeGp: [
          {
            required: true,
            message: '请输入质保期',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        schemeZbcost: [
          {
            required: true,
            message: '请输入总部成本价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        schemeDealerCost: [
          {
            required: true,
            message: '请输入经销商成本价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        schemeJzcost: [
          {
            required: true,
            message: '请输入家装成本价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        schemePrice: [
          {
            required: true,
            message: '请输入方案售价',
            trigger: 'blur'
          },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '格式有误',
            trigger: 'blur'
          }
        ],
        schemeContent: []
      },
      schemeFunOptions: [],
      schemeTypeOptions: [],
      productsOptions: [],
      //
      dialogVisible: false,
      assessData: {
        topData: {
          row1: '',
          row2: '',
          row3: ''
        },
        data: []
      },
      //
      pending: false
    }
  },
  computed: {
    ID() {
      return this.$route.query.id
    },
    isCopy() {
      return this.$route.query.copy
    }
  },
  async created() {
    this.initDictsOptions('product_fun', 'schemeFunOptions')
    this.initDictsOptions('project_type', 'schemeTypeOptions')
    this.initSchemeProducts()
  },
  async mounted() {
    if (this.ID) {
      try {
        const res = await schemeApi.detail(this.ID)
        const {
          schemeId,
          schemeName,
          schemeInName,
          schemeFun,
          schemeType,
          schemePersonPrice,
          schemeArea,
          schemeGp,
          schemeZbcost,
          schemeDealerCost,
          schemeJzcost,
          schemePrice,
          schemeContent,
          //
          schemeProducts,
          schemeAreas
        } = res.data
        const products = schemeProducts.map((pro) => {
          return {
            schemeProductName: pro.schemeProductName,
            schemeProductPrice: pro.schemeProductPrice,
            schemeProductCount: pro.schemeProductCount,
            schemeProductZprice: pro.schemeProductZprice,
            productId: pro.productId
          }
        })
        const areas = schemeAreas.map((area) => {
          return {
            schemeAreaArr: CityPicker.methods.getTextToValue({
              province: area.schemeAreaProvince,
              city: area.schemeAreaCity,
              area: area.schemeAreaArea
            }),
            dealerId: area.dealerId,
            dealerList: []
          }
        })
        areas.forEach((area) => {
          const { dealerId } = area
          this.handleCityPickChange(area.schemeAreaArr, area).then(() => {
            area.dealerId = dealerId
          })
        })
        this.formData = Object.assign(this.formData, {
          schemeId,
          schemeName,
          schemeInName,
          schemeFun,
          schemeType,
          schemePersonPrice,
          schemeArea,
          schemeGp,
          schemeZbcost,
          schemeDealerCost,
          schemeJzcost,
          schemePrice,
          schemeContent,
          products,
          areas
        })
      } catch (error) {
        console.log(error)
      }
    } else {
      this.resetForm()
    }
  },
  methods: {
    async initDictsOptions(dicts, listProps) {
      try {
        const res = await this.getDicts(dicts)
        if (res.code === 200) {
          this[listProps] = res.data.map((per) => ({
            label: per.dictLabel,
            value: per.dictValue
          }))
        }
      } catch (error) {
        console.log(error)
      }
    },
    async initSchemeProducts() {
      try {
        const res = await getSchemeProduct()
        if (res.code === 200) {
          this.productsOptions = res.data.map((per) => ({
            label: per.productName,
            value: per.productId,
            productFanPrice: per.productFanPrice
          }))
        }
      } catch (error) {
        console.log(error)
      }
    },
    getCityObj(addressArr) {
      let cityObj = CityPicker.methods.getValueTextObj(addressArr)
      return cityObj
    },
    handleProChange(e, proObj) {
      const pro = this.productsOptions.find((per) => per.value === e)
      if (!pro) {
        proObj.schemeProductName = undefined
        proObj.schemeProductPrice = undefined
        proObj.schemeProductZprice = undefined
        return
      }
      proObj.schemeProductName = pro.label
      proObj.schemeProductPrice = pro.productFanPrice
      if (proObj.schemeProductCount) {
        proObj.schemeProductZprice = proObj.schemeProductCount * proObj.schemeProductPrice
      }
    },
    handleProCountChange(e, proObj) {
      if (e !== undefined && proObj.schemeProductPrice) {
        proObj.schemeProductZprice = e * proObj.schemeProductPrice
      } else {
        proObj.schemeProductZprice = undefined
      }
    },
    handleProAdd() {
      this.formData.products.push({
        schemeProductName: undefined,
        schemeProductPrice: undefined,
        schemeProductCount: undefined,
        schemeProductZprice: undefined,
        productId: undefined
      })
    },
    handleProMinus(index) {
      this.formData.products.splice(index, 1)
    },
    async handleCityPickChange(e, area) {
      area.dealerId = undefined
      await this.reqDealerList(e, area)
    },
    async reqDealerList(addressArr, area) {
      let cityObj = this.getCityObj(addressArr)
      const res = await getDealerList({
        pageNum: 1,
        pageSize: 10000,
        dealerAddressArea: `${cityObj.province}${cityObj.city}${cityObj.area}`
      })
      area.dealerList = res.rows.map((per) => ({
        label: per.dealerName,
        value: per.dealerId
      }))
    },

    handleAreaDataAdd() {
      this.formData.areas.push({
        schemeAreaArr: [],
        dealerId: undefined,
        dealerList: []
      })
    },
    handleAreaDataMinus(index) {
      this.formData.areas.splice(index, 1)
    },
    submitForm() {
      this.$refs['elForm'].validate(async (valid) => {
        if (!valid) return

        const fetchData = this.getFetchData()
        // console.log(fetchData)
        this.pending = true
        try {
          const fetchFn = this.ID ? schemeApi.update : schemeApi.add
          const res = await fetchFn({
            ...fetchData
          })
          if (res.code === 200) {
            this.msgSuccess(res.msg)
            this.$closeNowTagsView()
          }
        } catch (error) {
          console.log(error)
        }
        this.pending = false
      })
    },
    submitAssess() {
      this.$refs['elForm'].validate(async (valid) => {
        if (!valid) return

        const fetchData = this.getFetchData()

        this.pending = true
        try {
          const res = await getSchemeAssess(fetchData)
          if (res.code === 200) {
            //
            this.dialogVisible = true
            const { topData, ...otherAssess } = res.data
            this.assessData.topData = topData
            this.assessData.data = Object.values(otherAssess).sort((a, b) => {
              return a.sort - b.sort
            })
          }
        } catch (error) {
          console.log(error)
        }
        this.pending = false
      })
    },
    getFetchData() {
      const fetchData = {
        ...this.formData
      }
      fetchData.areas = fetchData.areas.map((per) => {
        let cityObj = this.getCityObj(per.schemeAreaArr)

        return {
          schemeAreaProvince: cityObj.province,
          schemeAreaCity: cityObj.city,
          schemeAreaArea: cityObj.area,
          dealerId: per.dealerId
        }
      })
      return fetchData
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    }
  }
}
</script>

<style lang='scss' scoped>
.product_per_row {
  width: 100%;
  height: 60px;

  &:last-child .el-form-item {
    margin-bottom: 0;
  }
}
.assess_topData {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
  div:first-child {
    width: 100%;
    text-align: center;
    flex: 0 0 auto;
    margin-bottom: 10px;
    font-size: 16px;
  }
  justify-content: space-around;
  align-items: center;
}
.assess_data {
  display: flex;
  overflow-x: auto;
  .per_data {
    border: 1px solid #ccc;
    flex: 0 0 auto;
    div {
      padding: 10px 5px;
    }

    div:not(:first-child) {
      border-top: 1px solid #ccc;
    }
  }

  .per_data ~ .per_data {
    border-left: none;
  }
}
</style>


